  
  
/*  
* Copyright @ 2017 com.iflysse.trains  
* xebest-erp 下午7:32:15  
* All right reserved.  
*  
*/  
  
package com.xebest.web.service.impl;  

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xebest.common.enums.erp.storehouse.VenStoreAllotStatusEnum;
import com.xebest.common.enums.erp.storehouse.VenStoreDeliveryStatusEnum;
import com.xebest.common.enums.erp.storehouse.VenStoreDeliveryTypeEnum;
import com.xebest.common.enums.erp.storehouse.VenStoreReceiptStatusEnum;
import com.xebest.common.enums.erp.storehouse.VenStoreReceiptTypeEnum;
import com.xebest.util.seq.StoreHouseSeqUtil;
import com.xebest.web.mapper.read.XeVenStoreAllotDetailReadMapper;
import com.xebest.web.mapper.read.XeVenStoreAllotReadMapper;
import com.xebest.web.mapper.write.XeVenStoreAllotDetailWriteMapper;
import com.xebest.web.mapper.write.XeVenStoreAllotWriteMapper;
import com.xebest.web.model.XeVenStoreAllotDetailEntity;
import com.xebest.web.model.XeVenStoreAllotEntity;
import com.xebest.web.model.XeVenStoreDelivDetailEntity;
import com.xebest.web.model.XeVenStoreDeliveryEntity;
import com.xebest.web.model.XeVenStoreInventoryEntity;
import com.xebest.web.model.XeVenStoreReceiptDetailEntity;
import com.xebest.web.model.XeVenStoreReceiptEntity;
import com.xebest.web.service.XeVenStoreAllotService;
import com.xebest.web.service.XeVenStoreDelivService;
import com.xebest.web.service.XeVenStoreInventoryService;
import com.xebest.web.service.XeVenStoreReceiptService;
import com.xebest.web.view.ErpUserInfo;
import com.xebest.web.view.XeVenStoreAllotView;

  
/**  
 * @desc: xebest-erp  
 * @author: 杜春静 
 * @createTime: 2017年6月27日 下午7:32:15  
 * @history:  
 * @version: v1.0    
 */

@Service
public class XeVenStoreAllotServiceImpl implements XeVenStoreAllotService {
	
	private static final Logger log = LoggerFactory.getLogger(XeVenStoreAllotService.class);//日志记录类

	  
	@Autowired
	XeVenStoreAllotReadMapper xeVenStoreAllotReadMapper;//调拨单读
	
	@Autowired
	XeVenStoreAllotWriteMapper xeVenStoreAllotWriteMapper;//调拨单写
	
	@Autowired
	XeVenStoreAllotDetailReadMapper xeVenStoreAllotDetailReadMapper;//调拨单商品明细 读
	
	@Autowired
	XeVenStoreAllotDetailWriteMapper allotDetailWriteMapper;//调拨单商品明细 写
	
	@Autowired
	XeVenStoreDelivService storeDelivService; //出库单业务类
	@Autowired
	XeVenStoreReceiptService storeReceiptService;//入库单业务类
	@Autowired
	XeVenStoreInventoryService invService;//库存一览的业务类
	/*
	 * 查询调拨单列表
	 *(non-Javadoc)  
	 * @see com.xebest.web.service.XeVenStoreAllotService#queryStoreAllotList(java.util.Map)
	 */
	@Override
	public List<XeVenStoreAllotView> queryStoreAllotList(
			Map<String, Object> params) {
		  log.info("-----------查询调拨单列表-----------");
		return this.xeVenStoreAllotReadMapper.listStoreAllotByParam(params);  
	}
	/**
	 * 查询调拨单
	 * @author: 杜春静  
	 * @createTime: 2017年7月7日 下午5:50:46  
	 * @history:  
	 * @param param
	 * @return XeVenStoreAllotEntity
	 */
	public XeVenStoreAllotEntity queryStoreAllot(Map<String,Object> param){
		//查询调拨单
		XeVenStoreAllotEntity allot=this.xeVenStoreAllotReadMapper.getStoreAllotByMap(param);
		//查询调拨单商品明细
		List<XeVenStoreAllotDetailEntity>  allotDetailList = new ArrayList<XeVenStoreAllotDetailEntity>();
		allotDetailList = xeVenStoreAllotDetailReadMapper.listStoreAllotDetailByParam(param);
		allot.setAllotDetailList(allotDetailList);
		return allot;
	}
	 
	/*
	 * 更新调拨单  
	 *(non-Javadoc)  
	 * @see com.xebest.web.service.XeVenStoreAllotService#updateStoreAllot(com.xebest.web.model.XeVenStoreAllotEntity)  
	*/  
	
	@Override
	public int updateStoreAllot(XeVenStoreAllotEntity entity) throws Exception {
		int result = 0;
		//更新调拨单主表信息
		result =  xeVenStoreAllotWriteMapper.updateStoreAllotByCode(entity);
		if(result > 0 && null != entity.getAllotDetailList() && entity.getAllotDetailList().size() >0){
			//删除调拨单原有的调拨商品明细
			allotDetailWriteMapper.deleteAllotDetailByAllotCode(entity.getAllotCode());
			
			//重新添加调拨单明细
			result = allotDetailWriteMapper.batchInsertAllotDetail(entity.getAllotDetailList(),entity.getAllotCode());
		}
		return  result;
		
	}
	/**
	 * 审核调拨单
	 * @author: 杜春静  
	 * @createTime: 2017年7月5日 下午8:41:54  
	 * @history:  
	 * @param entity
	 * @return int
	 * @throws Exception 
	 */
	@Override
	public int checkStoreAllot(XeVenStoreAllotEntity entity) throws Exception{
		int result = 0;
		entity.setCheckTime(new Date());//设置审核时间

		//如果审核调拨单为通过时，首先根据调拨的出库的商品判断库存是否充足，如果库存充足，则进行出入库操作
		if(VenStoreAllotStatusEnum.FINISH.getValue().equals(entity.getAllotStatus())){
			//整个调拨单的调拨总额
			BigDecimal totalAllotAmount = new BigDecimal("0");
			//根据调拨单号查询调拨单商品明细
			Map<String, Object> param = new HashMap<String,Object>();
			param.put("userCode", entity.getUserCode());
			param.put("allotCode", entity.getAllotCode());
			List<XeVenStoreAllotDetailEntity> allotDetailList = xeVenStoreAllotDetailReadMapper.listStoreAllotDetailByParam(param);
			if(null != allotDetailList && allotDetailList.size() > 0){
				
				for(XeVenStoreAllotDetailEntity aDetail: allotDetailList){
					XeVenStoreInventoryEntity record = new XeVenStoreInventoryEntity();
					record.setUserCode(entity.getUserCode());
					record.setStoreId(entity.getSendStoreId());
					record.setProSku(aDetail.getProSku());
					record = invService.getStoreInvByParam(record);
					//如果没有库存直接审核失败
					if(null == record){
						return 1000;
					}
					//库存不足，直接审核失败
					BigDecimal useableInv = record.getUsableInv();
					BigDecimal allotNum = aDetail.getAllotNums(); 
					if(useableInv.compareTo(allotNum) < 0){
						return 1000;
					}
					//单个商品的调拨总额
					BigDecimal allotAmount = new BigDecimal("0");
					allotAmount = allotNum.multiply(aDetail.getProPrice());
					aDetail.setAllotAmount(allotAmount.setScale(2, BigDecimal.ROUND_HALF_UP));
					
					totalAllotAmount = totalAllotAmount.add(allotAmount);
				}
				entity.setAllotAmount(totalAllotAmount.setScale(2, BigDecimal.ROUND_HALF_UP));
				
				
				//获取出库单的单号
				String deliverOrder = StoreHouseSeqUtil.seqUtils.createDeliveryOrder();
				entity.setAllotOutOrder(deliverOrder);
				entity.setAllotOutTime(new Date());
				
				//获取入库单的单号
				String receiptOrder =  StoreHouseSeqUtil.seqUtils.createReceiptOrder();
				entity.setAllotInOrder(receiptOrder);
				entity.setAllotInTime(new Date());
				//更新调拨单主表信息
				result =  xeVenStoreAllotWriteMapper.updateStoreAllotByCode(entity);
				if(result > 0){
					//删除调拨单原有的调拨商品明细
					allotDetailWriteMapper.deleteAllotDetailByAllotCode(entity.getAllotCode());
					//重新添加调拨单明细
					result = allotDetailWriteMapper.batchInsertAllotDetail(allotDetailList,entity.getAllotCode());
				}
				
				
				//调拨单出库,首先获取出库单，更新到调拨单上
				result = allotToDeliv(entity,allotDetailList,deliverOrder);
				
				if(result > 0){
					//调拨入库
					result = allotToReceipt(entity,allotDetailList,receiptOrder);
				}
			} else {
				return 2000;
			}
		} else if(VenStoreAllotStatusEnum.REJECTED.getValue().equals(entity.getAllotStatus())){
			//更新调拨单主表信息
			result =  xeVenStoreAllotWriteMapper.updateStoreAllotByCode(entity);
		}
		return  result;
	}
	/**
	 * 调拨出库
	 * @author: 杜春静  
	 * @createTime: 2017年7月6日 下午3:55:27  
	 * @history:  
	 * @param entity
	 * @param allotDetailList
	 * @return
	 * @throws Exception int
	 */
	public int allotToDeliv(XeVenStoreAllotEntity entity,List<XeVenStoreAllotDetailEntity> allotDetailList,String deliverOrder) throws Exception{
		int result = 0;
		//封装出库单
		XeVenStoreDeliveryEntity delivEntity = new XeVenStoreDeliveryEntity();
		delivEntity.setDeliveryOrder(deliverOrder);
		delivEntity.setUserCode(entity.getUserCode());
		delivEntity.setRelationOrder(entity.getAllotCode());
		delivEntity.setStoreId(entity.getSendStoreId());
		delivEntity.setStoreName(entity.getSendStoreName());
		delivEntity.setDeliveryType(VenStoreDeliveryTypeEnum.ALLOT_DELIVERY.getValue());
		delivEntity.setDeliveryStatus(VenStoreDeliveryStatusEnum.DELIVERY.getValue());
		delivEntity.setCreateUser(entity.getCreateUser());
		delivEntity.setModifyUser(entity.getModifyUser());
		//封装出库商品明细
		List<XeVenStoreDelivDetailEntity> delivDetailList = new ArrayList<XeVenStoreDelivDetailEntity>();
		for(XeVenStoreAllotDetailEntity allotDetail:allotDetailList){
			XeVenStoreDelivDetailEntity delivDetail = new XeVenStoreDelivDetailEntity();
			delivDetail.setProSku(allotDetail.getProSku());
			delivDetail.setProName(allotDetail.getProName());
			delivDetail.setProOutNum(allotDetail.getAllotNums());
			delivDetail.setProMainImg(allotDetail.getProMainImg());
			delivDetail.setProNum(allotDetail.getProNum());
			delivDetail.setDelivBatchPrice(allotDetail.getProPrice());
			delivDetail.setProSpecName(allotDetail.getProSpecName());
			delivDetail.setProSpecValue(allotDetail.getProSpecValue());
			delivDetail.setProCategoryId(allotDetail.getProCategoryId());
			delivDetail.setProCategoryName(allotDetail.getProCategoryName());
			delivDetail.setProPricingType(allotDetail.getPricingType());
			delivDetail.setProUnit(allotDetail.getProUnit());
			delivDetail.setCreateUser(entity.getCreateUser());
			delivDetail.setModifyUser(entity.getModifyUser());
			delivDetailList.add(delivDetail);
		}
		delivEntity.setDelivDtailList(delivDetailList);
		//进行出库
		result = storeDelivService.saveDeliv(delivEntity);
		return result;
	}
	/**
	 * 调拨入库
	 * @author: 杜春静  
	 * @createTime: 2017年7月6日 下午3:57:36  
	 * @history:  
	 * @param entity
	 * @param allotDetailList
	 * @return
	 * @throws Exception int
	 */
	public int allotToReceipt(XeVenStoreAllotEntity entity,List<XeVenStoreAllotDetailEntity> allotDetailList, String receiptOrder) throws Exception{  
		int result = 0; 
		//封装入库单主表信息
		XeVenStoreReceiptEntity receiptEntity = new XeVenStoreReceiptEntity();
		receiptEntity.setReceiptOrder(receiptOrder);
		receiptEntity.setStoreId(entity.getReceiptStoreId());
		receiptEntity.setStoreName(entity.getReceiptStoreName());
		receiptEntity.setUserCode(entity.getUserCode());
		receiptEntity.setRelationOrder(entity.getAllotCode());
		receiptEntity.setReceiptType(VenStoreReceiptTypeEnum.DB_RECEIPT.getValue());
		receiptEntity.setReceiptStatus(VenStoreReceiptStatusEnum.RECEIPT.getValue());
		receiptEntity.setCreateUser(entity.getCreateUser());
		receiptEntity.setModifyUser(entity.getModifyUser());
		//封装入库单商品明细
		List<XeVenStoreReceiptDetailEntity> receiptDetailList = new ArrayList<XeVenStoreReceiptDetailEntity>();
		for(XeVenStoreAllotDetailEntity allotDetail:allotDetailList){
			XeVenStoreReceiptDetailEntity receiptDetail = new XeVenStoreReceiptDetailEntity();
			receiptDetail.setProSku(allotDetail.getProSku());
			receiptDetail.setBatchPrice(allotDetail.getProPrice());
			receiptDetail.setProMainImg(allotDetail.getProMainImg());
			receiptDetail.setProNum(allotDetail.getProNum());
			receiptDetail.setProCategoryId(allotDetail.getProCategoryId());
			receiptDetail.setProCategoryName(allotDetail.getProCategoryName());
			receiptDetail.setProUnit(allotDetail.getProUnit());
			receiptDetail.setProName(allotDetail.getProName());
			receiptDetail.setProSpecName(allotDetail.getProSpecName());
			receiptDetail.setProSepcValue(allotDetail.getProSpecValue());
			receiptDetail.setProPricingType(allotDetail.getPricingType());
			receiptDetail.setCurrentInNum(allotDetail.getAllotNums());
			receiptDetail.setCreateUser(allotDetail.getCreateUser());
			receiptDetail.setModifyUser(allotDetail.getModifyUser());
			receiptDetailList.add(receiptDetail);
		}
		receiptEntity.setReceiptDetailList(receiptDetailList);
	  
		//进行入库
		result = storeReceiptService.saveStoreReceipt(receiptEntity);
		return result;
	}
	/*  
	 * 批量废弃调拨单
	 *(non-Javadoc)  
	 * @see com.xebest.web.service.XeVenStoreAllotService#updateDiscardStoreAllot(java.util.List)  
	*/  
	@Override
	public int updateDiscardStoreAllot(String[] allotCodes,ErpUserInfo userInfo) throws Exception {
		int result = 0; 
		  List<XeVenStoreAllotEntity> entityList = new ArrayList<XeVenStoreAllotEntity>();
		  entityList = xeVenStoreAllotReadMapper.checkUsableAllot(allotCodes, userInfo.getUserCode(), VenStoreAllotStatusEnum.NO_REVIEW.getValue());
		  
		  if(null != entityList && entityList.size() > 0){
			  for(XeVenStoreAllotEntity entity : entityList){
				  entity.setAllotStatus(VenStoreAllotStatusEnum.DISCARDED.getValue());
			  }
			  result = xeVenStoreAllotWriteMapper.batchUpdateStoreAllot(entityList);
		  }
		return result;  
		
	}


	  
	/*  
	 * 查询调拨单商品明细
	 *(non-Javadoc)  
	 * @see com.xebest.web.service.XeVenStoreAllotService#listStoreAllotByParam(java.util.Map)  
	*/  
	@Override
	public List<XeVenStoreAllotDetailEntity> listAllotDetailByParam(
			Map<String, Object> param) {
		  
		return xeVenStoreAllotDetailReadMapper.listStoreAllotDetailByParam(param);  
		
	}


	  
	/*  
	 * 添加调拨单
	 *(non-Javadoc)  
	 * @see com.xebest.web.service.XeVenStoreAllotService#saveStoreAllot(com.xebest.web.model.XeVenStoreAllotEntity)  
	*/  
	
	@Override
	public int saveStoreAllot(XeVenStoreAllotEntity entity) throws Exception {
		int result = 0;
		log.info("添加调拨单主表");
		String allotCode = StoreHouseSeqUtil.seqUtils.createAllortCode();
		entity.setAllotCode(allotCode);
		entity.setAllotStatus(VenStoreAllotStatusEnum.NO_REVIEW.getValue());
		result = xeVenStoreAllotWriteMapper.insertStoreAllot(entity);
		log.info("添加调拨单主表，添加结果：{}"+result);
		 if(result > 0){
			 
			 if(entity.getAllotDetailList() != null && entity.getAllotDetailList().size() > 0 ){
				 
				 result = allotDetailWriteMapper.batchInsertAllotDetail(entity.getAllotDetailList(),allotCode);
				 log.info("添加调拨单从表，添加结果：{}"+result);
			 }
		 }
		return result;  
		
	}
}
  
